//
//  GetEnButtonImageButton.m
//  ImageReplacer
//
//  Created by Tyler Powell on 5/7/12.
//  Copyright (c) 2012 Georgia Institute of Technology. All rights reserved.
//

#import "GetEnButtonImageButton.h"

@implementation GetEnButtonImageButton
@synthesize  imageTable;
@synthesize writer;
- (IBAction)openFile:(id)pId;
{
	NSOpenPanel* openDlg = [NSOpenPanel openPanel];
	//NSWorkspace* workspace = [NSWorkspace sharedWorkspace];
	NSArray* fileTypes = [NSArray arrayWithObject:@"png"];
	[openDlg setCanChooseFiles:YES];
	[openDlg setCanChooseDirectories:YES];
	[openDlg setAllowsMultipleSelection:YES];
	[openDlg setRequiredFileType:@"png"];
	[openDlg setAllowedFileTypes:fileTypes];
	[openDlg setAllowsOtherFileTypes:NO];
    
	
	if([openDlg runModalForDirectory:nil file:nil types:fileTypes] == NSOKButton)
	{
		NSArray* files = [openDlg URLs];
		
		//NSLog(@"Is of type: %@", [[files objectAtIndex:0]pathExtension]);
		for(int i=0; i<[files count]; i++)
		{
			NSURL* url = [files objectAtIndex:i];
			if ([self isDirectory:url]) {
				NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:[url path]];
				NSString* file;
				while (file = [enumerator nextObject]) {
					//BOOL isDir = NO;
					//NSLog(file);
					//[[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",[url path],file] isDirectory:&isDir];
					NSString* fileFromPath = [[url path] stringByAppendingFormat:@"/%@", file];
                    if ([[file pathExtension] isEqualToString:@"png"]) {
                        [writer addEnabledButton:fileFromPath];
                    }
				}
			} else {
                NSString* fileName = [url path];
                //NSLog(fileName);
                [writer addEnabledButton:fileName];
                //[workspace openFile:fileName];
            }
		}
	}
    [imageTable reloadData];
    
}
-(BOOL) isDirectory:(NSURL*) url;
{
	return[[url pathExtension]isEqualToString:@""];
}
@end
